/**
 * Description:
 * Class Name:LoginFrame
 * Date:2022/4/4 21:09
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第13章_MySQL数据库和JDBC编程._13_4_执行SQL语句的方式._13_4_3_使用PreparedStatement执行SQL语句;

import javax.swing.*;
import java.awt.*;
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;

public class LoginFrame {
    private final String PROP_FILE = "./Chapter_13_mysql.ini";
    private String driver;
    private String url;
    private String user;
    private String pwd;

    // 登录界面的GUI组件
    private JFrame jf = new JFrame("登录");
    private JTextField userField = new JTextField(20);
    private JTextField pwdField = new JTextField(20);
    private JButton loginButton = new JButton("click to login");

    public void init() throws Exception{
        var props = new Properties();
        props.load(new FileInputStream(PROP_FILE));
        driver = props.getProperty("driver");
        url = props.getProperty("url");
        user = props.getProperty("user");
        pwd = props.getProperty("pwd");
    }
    public void login() throws Exception{
        // 为登录按钮添加事件监听器
        loginButton.addActionListener(e -> {
            if (validate(userField.getText(), pwdField.getText())){
                JOptionPane.showMessageDialog(jf, "登录成功");
            }
            else {
                JOptionPane.showMessageDialog(jf, "登录失败");
            }
        });
        // 为GUI组件在框架上布局
        jf.add(userField, BorderLayout.NORTH);
        jf.add(pwdField);
        jf.add(loginButton, BorderLayout.SOUTH);
        jf.pack();              // 打包
        jf.setVisible(true);    //设置GUI对用户可见
    }
    private boolean validate(String userName, String userPass){
        // 执行查询的SQL语句
        var sql = "select * from jdbc_test " +
                " where jdbc_name = '" + userName +
                "' and jdbc_desc = '" + userPass + "'";
        System.out.println(sql);
        try (Connection connection = DriverManager.getConnection(url, user, pwd);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)){
            // 如果查询的ResultSet里有超过1条的记录，则登录成功
            if (resultSet.next()){
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws Exception{
        var lf = new LoginFrame();
        lf.init();
        // 加载驱动
        Class.forName(lf.driver);
        lf.login();
    }
}
